package lib;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class OperationJNDI {
	/*
	 * Definir le parametre pour init le serveur JNDI
	 */
	public final String url="ldap://localhost:389/dc=home,dc=com";
	public final String secu_principal="cn=admin,dc=home,dc=com";
	public final String secu_authen="simple";
	public final String passwd="1234";
	private DirContext ctx=null;
	public   void initJNDI()
	{
	    Hashtable<String,String> env = new Hashtable<String,String>(11);
   	
    		env.put(Context.INITIAL_CONTEXT_FACTORY, 
          		"com.sun.jndi.ldap.LdapCtxFactory");
    		env.put(Context.PROVIDER_URL, url);
    		env.put(Context.SECURITY_AUTHENTICATION,secu_authen);
        	env.put(Context.SECURITY_PRINCIPAL, secu_principal);
        	env.put(Context.SECURITY_CREDENTIALS, passwd);
		
		try {
			ctx = new InitialDirContext(env);
			System.out.println("initiation est  reussir");
				

		} catch (NamingException e) {
			
			e.printStackTrace();
		} catch(NullPointerException e)
		{
			e.printStackTrace();
		}
	}
	
	public void bind(String bindname,Object obj,DirContext ctxobject)
	{
		try {
			ctxobject.bind(bindname,obj);
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
   public void bind(String bindname,DirContext ctx)
   {
	   Attributes attrs = new BasicAttributes(true);
	   attrs.put(new BasicAttribute("objectclass","inetorgperson"));
	   attrs.put(new BasicAttribute("cn","nchen"));
	   attrs.put(new BasicAttribute("sn","nchen"));
	   try {
		   ctx.createSubcontext(bindname, attrs);
		   
		} catch (NamingException e) {
			e.printStackTrace();
		}
	   
   }
   public void unbind(String name)
   {
	   try {
		   ctx.unbind(name);
	   	} 
	   catch (NamingException e) {
		   e.printStackTrace();
	   }
   }
	public Object resolve(String name)
	{
		Object o=null;
		try {
			o = ctx.lookup(name);
		} catch (NamingException e) {
		
			e.printStackTrace();
		}
		return o;
	}
	public DirContext getCtx() {
		return ctx;
	}
	public void setCtx(DirContext ctx) {
		this.ctx = ctx;
	}
	public static void main(String[] args) {
		OperationJNDI op=new OperationJNDI();
		op.initJNDI();
		DirContext ctx=op.getCtx();
		try {
		
			DirContext ctxobject=(DirContext)ctx.lookup("cn=admin");
			/*Attributes attrs = new BasicAttributes(true);
			attrs.put(new BasicAttribute("objectclass","inetorgperson"));
			attrs.put(new BasicAttribute("cn","nchen"));
  			attrs.put(new BasicAttribute("sn","nchen"));
  			ctxpeople.createSubcontext("uid =nan", attrs);*/
			//op.bind("nan's object",new Personne("nan"),ctxobject);
			ctx.close();
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}

}
